/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "aslist.h"

CORBA::ULong cASList::registerSM(const char* objref )
{
    mutex.lock();
    objrefs[_id]=objref;
    objrefs_usage[_id]=false;
    mutex.unlock();
    FILE_LOG(logDEBUG)<<"Number of registered SM:"<<objrefs.size()<<endl;
    FILE_LOG(logDEBUG)<<"Number of usage ids:"<<objrefs_usage.size()<<endl;
    FILE_LOG(logDEBUG)<<"Registering SM "<<_id<<" with the objeref: "<<objref<<std::endl;
    FILE_LOG(logDEBUG)<<"registerSM called!"<<std::endl;
    return _id++;


}


CORBA::Boolean cASList::releasSM(CORBA::ULong id)
{
    mutex.lock();
    objrefs_usage[id]=false;
    mutex.unlock();
    FILE_LOG(logDEBUG)<<"Releases SM with ID:"<<id<<endl;
    return true;
}


char* cASList::allocateSM(unsigned int& id)
{
    mutex.lock();
    if (objrefs_usage.size()>0)
    {
        map<unsigned int,bool>::iterator it;
        it=objrefs_usage.begin();
        unsigned int _id=(*it).first;
        FILE_LOG(logDEBUG)<<"Found SM with ID:"<<_id<<endl;
        objrefs_usage.erase(_id);
        FILE_LOG(logDEBUG)<<"FOUND SM with SIOR:"<<objrefs[_id]<<endl;
        id=_id;
        mutex.unlock();
        return const_cast<char *>( objrefs[_id].c_str());
    }
    else
    {
        id=0;
        char * cstr=new char[6];
        strcpy(cstr,"empty");
        mutex.unlock();
        return cstr;
    }

}
CORBA::Boolean cASList::unregisterSM(CORBA::ULong id)
{

    FILE_LOG(logDEBUG) <<"unregisterSM called for SM #"<<id <<std::endl;
    FILE_LOG(logDEBUG)<<"Number of ids:"<<objrefs.size()<<endl;
    mutex.lock();
    objrefs_usage.erase(id);
    objrefs.erase(id);
    mutex.unlock();
    FILE_LOG(logDEBUG)<<"Number of ids:"<<objrefs.size()<<endl;

}
